package cn.itcast.netty.c5;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import static cn.itcast.netty.c4.TestSlice.log;

public class TestLengthFieldDecoder {
    public static void main(String[] args) {
        EmbeddedChannel channel = new EmbeddedChannel(
                //指定消息长度 + 内容 来解决粘包 半包的方法
                new LengthFieldBasedFrameDecoder(1024,0,4,1,5),
                new LoggingHandler(LogLevel.DEBUG)
        );

        //4个字节长度 + 实际内容
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        send(buf,"Hello, World");
        send(buf,"Hi");
//        log(buf);
        channel.writeInbound(buf);
    }

    private static void send(ByteBuf buf,String context){
        byte[] bytes = context.getBytes();
        int length = bytes.length;
        buf.writeInt(length);
        buf.writeByte(1);
        buf.writeBytes(bytes);
    }
}
